package com.paishen.peiniwan.module.login;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.dialog.SelectionDialog;
import com.paishen.common.dialog.picker.DataPickerDialog;
import com.paishen.common.dialog.picker.DictPickerDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.LogUtil;
import com.paishen.common.util.NetworkUtil;
import com.paishen.common.util.SpfsUtil;
import com.paishen.peiniwan.ActivityCollector;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.UserDao;
import com.paishen.peiniwan.database.util.ModelConverter;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.User;
import com.paishen.peiniwan.frame.http.response.HttpRespUser;
import com.paishen.peiniwan.module.MainActivity;
import com.squareup.okhttp.Request;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class RegisterCompleteActivity extends BaseActivity {
    public static final String EXTRA_INVITE = "extra_invite";
    public static final String EXTRA_PASSWORD = "extra_password";
    public static final String EXTRA_PHONE = "extra_phone";
    private String password, phone, invite;

    private ImageView imgAvatar;
    private EditText edNickname;
    private TextView txGender, txAge, txCity, txSalary;

    private int mGender;
    private String pictureUrl;
    private SelectionDialog dlgGetPhoto, dlgGender;
    private DataPickerDialog dlgAge,dlgSalary;
    private DictPickerDialog dlgAddress;

    private AlertDialog dlgConfirm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        phone = getIntent().getStringExtra(EXTRA_PHONE);
        password = getIntent().getStringExtra(EXTRA_PASSWORD);
        invite = getIntent().getStringExtra(EXTRA_INVITE);
        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(password)) {
            BaseUtil.showToast("registerComplete fail ! empty phone or password");
            finish();
            return;
        }

        setContentView(R.layout.activity_register_complete);

        BaseUtil.setStatusBarDarkMode(true, this);

        View layContainer = findViewById(R.id.lay_container);
        layContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseUtil.hideSoftInputFromWindowAlways(RegisterCompleteActivity.this);
            }
        });

        layContainer.setPadding(0, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);

        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        imgAvatar = (ImageView) findViewById(R.id.img_avatar);
        edNickname = (EditText) findViewById(R.id.ed_nickname);
        txAge = (TextView) findViewById(R.id.tx_age);
        txGender = (TextView) findViewById(R.id.tx_gender);
        txCity = (TextView) findViewById(R.id.tx_city);
        txSalary = (TextView) findViewById(R.id.tx_salary);

        imgAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showGetPhotoDialog();
            }
        });

        View.OnClickListener l = new View.OnClickListener() {
            private long timestamp;

            @Override
            public void onClick(View v) {
                long curr = System.currentTimeMillis();
                if (curr - timestamp < 500) return;
                timestamp = curr;

                switch (v.getId()) {
                    case R.id.lay_gender:
                        showGenderDialog();
                        break;
                    case R.id.lay_age:
                        showAgeDialog();
                        break;
                    case R.id.lay_city:
                        showAddressDialog();
                        break;
                    case R.id.lay_salary:
                        showSalaryDialog();
                        break;
                }
            }
        };

        findViewById(R.id.lay_gender).setOnClickListener(l);
        findViewById(R.id.lay_age).setOnClickListener(l);
        findViewById(R.id.lay_city).setOnClickListener(l);
        findViewById(R.id.lay_salary).setOnClickListener(l);

        findViewById(R.id.tx_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkRegisterInfo()) {
                    showConfirmDialog();
                }
            }
        });

        findViewById(R.id.tx_register_agreement).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegisterCompleteActivity.this, RegisterRulesActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseUtil.hideSoftInputFromWindowAlways(this);
    }

    private void showConfirmDialog() {
        if (dlgConfirm == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            dlgConfirm = builder.setTitle(R.string.tips).setMessage(R.string.register_tip_gender).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    requestUserRegister();
                    dlgConfirm.dismiss();
                }
            }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dlgConfirm.dismiss();
                }
            }).create();
        }
        dlgConfirm.show();
    }

    private void requestUserRegister() {
        File photo = new File(pictureUrl);

        String nickname = edNickname.getText().toString();
        String age = txAge.getText().toString();
        String city = txCity.getText().toString();
        String salary = txSalary.getText().toString();

        String platform = "paishen";
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(),
                    PackageManager.GET_META_DATA);
            platform = appInfo.metaData.getString("UMENG_CHANNEL");

        } catch (PackageManager.NameNotFoundException ignored) {
        }

        final LoadingDialog dlgLoading = new LoadingDialog.Builder(this).create();
        dlgLoading.show();

        PnwHttpManager.User.completeReg(TAG, nickname, photo, mGender, age, city, salary, password, invite, platform, new PnwOkCallbackAdapter<HttpRespUser<User>>() {
            @Override
            public void onResponse(HttpRespUser<User> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    SpfsUtil.write(C.sp.CURRENT_LOGIN_USER_ID, response.user.id);
                    UserDao userDao = App.i().getDaoSession(response.user.id).getUserDao();
                    com.paishen.peiniwan.database.User dbUser = userDao.queryBuilder().where(UserDao.Properties.Id.eq(response.user.id)).unique();
                    dbUser = ModelConverter.mergeOrReplace(dbUser, response.user);
                    App.i().setUser(dbUser);
                    dbUser.setPhone(phone);
                    dbUser.setPassword(password);

                    dbUser.setApp_auto_login(true);
                    userDao.insertOrReplace(dbUser);

                    String easemob_username = dbUser.getEasemob_username();
                    String easemob_password = dbUser.getEasemob_password();
                    EMClient.getInstance().login(easemob_username, easemob_password, new EMCallBack() {
                        @Override
                        public void onSuccess() {
                            if (!isFinishing()) {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        LogUtil.d("EMChatManager onSuccess 登陆聊天服务器成功！");
                                        dlgLoading.dismiss();
                                        Intent intent = new Intent(RegisterCompleteActivity.this, MainActivity.class);
                                        startActivity(intent);
                                        ActivityCollector.finishAllExcept(MainActivity.class);
                                    }
                                });
                            }
                        }

                        @Override
                        public void onProgress(int progress, String status) {
                            LogUtil.d("EMChatManager onProgress progress:" + progress + "#status:" + status);
                        }

                        @Override
                        public void onError(int code, String message) {
                            LogUtil.d("EMChatManager onError 登陆聊天服务器失败！");
                            if (!isFinishing()) {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        dlgLoading.dismiss();
                                        BaseUtil.showToast(NetworkUtil.isNoInternet() ? R.string.error_net : R.string.error_request);
                                    }
                                });
                            }
                        }
                    });
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });
    }

    private boolean checkRegisterInfo() {
        boolean result = true;
        if (TextUtils.isEmpty(pictureUrl)) {
            result = false;
            BaseUtil.showToast(R.string.register_avatar_setting);
        } else if (edNickname.getText().length() < 2) {
            result = false;
            BaseUtil.showToast(R.string.register_fail_nickname_5);
        } else if (BaseUtil.isConSpeCharacters(edNickname.getText().toString())) {
            result = false;
            BaseUtil.showToast(R.string.register_fail_nickname_7);
        } else if (TextUtils.isEmpty(txGender.getText())) {
            result = false;
            BaseUtil.showToast(R.string.register_input_gender);
        } else if (TextUtils.isEmpty(txAge.getText())) {
            result = false;
            BaseUtil.showToast(R.string.register_input_age);
        } else if (TextUtils.isEmpty(txCity.getText())) {
            result = false;
            BaseUtil.showToast(R.string.register_input_city);
        } else if(TextUtils.isEmpty(txSalary.getText())) {
            result = false;
            BaseUtil.showToast(R.string.register_input_salary);

        }
        return result;
    }

    private void showGetPhotoDialog() {
        if (dlgGetPhoto == null) {
            List<SelectionDialog.Menu> menuList = new ArrayList<>();
            menuList.add(new SelectionDialog.Menu(getString(R.string.frame_photo_from_camera), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openCamera();
                    dlgGetPhoto.dismiss();

                }
            }));

            menuList.add(new SelectionDialog.Menu(getString(R.string.frame_photo_from_album), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openPhotos();
                    dlgGetPhoto.dismiss();
                }
            }));
            SelectionDialog.Builder builder = new SelectionDialog.Builder(this);
            dlgGetPhoto = builder.setMenuList(menuList).create();
        }

        dlgGetPhoto.show();
    }

    private void showGenderDialog() {
        if (dlgGender == null) {
            List<SelectionDialog.Menu> menuList = new ArrayList<>();
            menuList.add(new SelectionDialog.Menu(getString(R.string.date_gender_boy), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    txGender.setText(R.string.date_gender_boy);
                    mGender = PnwHttpManager.Square.SQUARE_FILTER_GENDER_MALE;
                    dlgGender.dismiss();
                }
            }));

            menuList.add(new SelectionDialog.Menu(getString(R.string.date_gender_girl), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    txGender.setText(R.string.date_gender_girl);
                    mGender = PnwHttpManager.Square.SQUARE_FILTER_GENDER_FEMALE;
                    dlgGender.dismiss();
                }
            }));
            SelectionDialog.Builder builder = new SelectionDialog.Builder(this);
            dlgGender = builder.setMenuList(menuList).create();
        }

        dlgGender.show();
    }

    private void showAgeDialog() {
        if (dlgAge == null) {
            List<String> data = new ArrayList<>();
            data.addAll(d(18, 22, getString(R.string.profile_age_unit)));
            dlgAge = new DataPickerDialog.Builder(this).setTitle(getString(R.string.profile_age)).setSelection(7).setUnit("").setData(data)
                    .setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                        @Override
                        public void onDataSelected(String itemValue) {
                            txAge.setText(itemValue);
                        }
                    }).create();
        }
        if (!TextUtils.isEmpty(txAge.getText())) dlgAge.setSelection(txAge.getText().toString());
        dlgAge.show();
    }
    private void showSalaryDialog(){
        if (dlgSalary == null) {
            List<String> data = Arrays.asList(getResources().getStringArray(R.array.profile_salary));
            dlgSalary = new DataPickerDialog.Builder(this).setTitle(getString(R.string.profile_constellation)).setUnit("").setData(data)
                    .setOnDataSelectedListener(new DataPickerDialog.OnDataSelectedListener() {
                        @Override
                        public void onDataSelected(String itemValue) {
                            txSalary.setText(itemValue);
                        }
                    }).create();
        }
        if (!TextUtils.isEmpty(txSalary.getText()))
            dlgSalary.setSelection(txSalary.getText().toString());
        dlgSalary.show();
    }

    private void showAddressDialog() {
        if (dlgAddress == null) {
            dlgAddress = new DictPickerDialog.Builder(this).setOnDictSelectedListener(new DictPickerDialog.OnDictSelectedListener() {
                @Override
                public void onDictSelected(String[] itemValue) {
                    txCity.setText(itemValue[0] + "-" + itemValue[1]);
                }
            }).create();
        }
        dlgAddress.show();
    }


    @Override
    public void onEventMainThread(BusEvent event) {
        super.onEventMainThread(event);
        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            switch (event.action) {
                case BusEvent.ACTION_PICTURE_QUERY_OUT:
                    String url = String.valueOf(event.content);

                    Glide.with(this).load(url).bitmapTransform(App.i().getCropCircleTransformation()).into(imgAvatar);
                    pictureUrl = url;
                    break;
            }
        }
    }

    private final List<String> d(int startNum, int count, String unit) {
        String[] values = new String[count];
        for (int i = startNum; i < startNum + count; i++) {
            String tempValue = (i < 10 ? "0" : "") + i;
            values[i - startNum] = tempValue + unit;
        }
        return Arrays.asList(values);
    }
}
